﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using Mrsoft.Common;
using Mrsoft.Controls;
using System.Runtime.InteropServices;

namespace Mrsoft.UI
{

    [Guid("CAAAF3AB-DD2C-4575-A076-76B99E44F52C")]
    public class MainPlugin : IMrsoft
    {

        /// <summary>
        /// 插件入口执行点
        /// </summary>
        public void Run() {
            //保证软件运行的独立性
            bool isFirstInstance;
            using (var mtx = new Mutex(true, "mrsoft", out isFirstInstance)) {
                Start();
                if (isFirstInstance) {
                    //try { OldFileDelete(); }
                    //catch { }
                    AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler;
                    if (Login()) {
                        Application.Run(new FrmMain());
                    }
                } else {
                    NativeMethods.ShowStartedWindow("小懒虫");
                }
                Stop();
            }
        }


        public void Init() {
            //启动事件
            AppStartEvent += MuYue.Config.AppConfigThreadManger.Start; ;
            AppStartEvent += MuYue.Log.LogService.Start;
            //停止事件
            AppStopEvent += MuYue.Config.AppConfigThreadManger.Stop;
            AppStopEvent += MuYue.Log.LogService.Stop;
        }

        public static event Action AppStartEvent;
        public static event Action AppStopEvent;

        /// <summary>
        /// 先进行响应的数据绑定然后启动
        /// </summary>
        private void Start() {
            Init();
            if (AppStartEvent != null)
                AppStartEvent();
        }

        /// <summary>
        /// 通知停止工作了
        /// </summary>
        private void Stop() {
            if (AppStopEvent != null)
                AppStopEvent();
        }

        /// <summary>
        /// 登陆软件并返回登陆结果
        /// </summary>
        /// <returns></returns>
        private bool Login() {
            var frmLogin = new FrmLogin();
            Application.Run(frmLogin);
            frmLogin.Dispose();
            return LoginResult.Login;
        }

        // 非常规异常捕获处理 
        private static void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e) {
            var w = new StreamWriter(@".\错误记录.log", false);
            w.Write(e.ToString());
            w.Close();
            MessageBox.Show("软件出现了异常！请把文件夹下的错误记录发给漠然！");
        }

        /// <summary>
        /// 加载皮肤文件
        /// </summary>
        /// <param name="frm">皮肤加载的窗口</param>
        /// <param name="control">自定义的system控件</param>
        public static void FrmSkinLoad(Form frm, SystemControl control) {
            ImageDrawing.BeSuittable(frm);
            var image = new Config<string>(".\\common.cfg", "skin/image", ".\\system\\skin.jpg");
            var color = new Config<string>(".\\common.cfg", "skin/color", "snow");
            if (File.Exists(image.Value)) {
                using (FileStream pfs = File.OpenRead(image.Value)) {
                    control.ForeColor = Color.FromName(color.Value);
                    frm.BackgroundImage = Image.FromStream(pfs);
                    pfs.Close();
                }
            }
        }

        /// <summary> 
        /// 设置窗口的皮肤图像
        /// </summary>
        /// <param name="frm">发送请求的窗口用于及时反馈</param>
        /// <param name="control">窗口上的SystemControl控件</param>
        public static void SetFrmSkin(Form frm, SystemControl control) {
            using (var dialog = new OpenFileDialog { Filter = @"背景图片|*.jpg;*.bmp;*.png" }) {
                var dialogResult = dialog.ShowDialog();
                if (dialogResult == DialogResult.OK) {
                    new Config<string>("./common.cfg", "skin/image", @".\system\skin.jpg").Value = dialog.FileName;
                    FrmSkinLoad(frm, control);
                }
            }
        }


        //去除冗余文件
        private void OldFileDelete() {
            //设置格式: 小写格式的文件名
            var dllSets = new HashSet<string>{
                                   "7z.dll",
                                   "update.dll",
                                   "mrsoft.controls.dll",
                                   "sevenzipsharp.dll",
                                   "core.dll",
                                   "mrsoft.dll",
                                   "SQLite.Interop.dll".ToLower(),
                                   "System.Data.SQLite.dll".ToLower(),
                                   "mrsoft.log.dll",
                                   "muyue.dll",
                                   "Newtonsoft.Json.dll".ToLower(),
                               };

            var files = Directory.GetFiles("./");
            foreach (var file in files) {
                try {
                    if (file.EndsWith(".dll", StringComparison.CurrentCultureIgnoreCase)
                        && !dllSets.Contains(file.Replace("./", "").ToLower()))
                        File.Delete(file);
                }
                catch { }
            }

            var oldfiles = new HashSet<string> {
                "dns.ini", 
                "hwnd.bin",
                "update.exe",
                "插件\\xx.dll"
            };

            foreach (var file in oldfiles) {
                try {
                    //出去掉冗余文件
                    var fullFileName = Path.Combine(Application.StartupPath, file);
                    if (File.Exists(fullFileName)) {
                        File.Delete(fullFileName);
                    }
                }
                catch { }
            }
        }
    }
}
